package com.net.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName NettyServerInitializer
 * @Description TODO
 * @Author zhuchen216628
 * @Date 2018/9/28 10:49
 * @Version 1.0
 **/
@Component
public class NettyAppServerInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private ConnectManager connectManager;

    @Autowired
    private BeanFactory beanFactory;

    public NettyAppServerInitializer(){

    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 以("\n")为结尾分割的 解码器
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

        // 字符串解码 和 编码
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());

        // 自己的逻辑Handler
        // 自己的逻辑Handler
        NettyAppServerHandler nettyAppServerHandler = (NettyAppServerHandler) beanFactory.getBean("nettyAppServerHandler");
        pipeline.addLast("handler", nettyAppServerHandler);
    }
}
